package com.ebei.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ebei.admin.common.constant.Constants;
import com.ebei.admin.common.util.AuthRealm;
import com.ebei.admin.common.util.TreeUtil;
import com.ebei.admin.mapper.SysRoleMapper;
import com.ebei.admin.model.dto.RoleDTO;
import com.ebei.admin.model.dto.RoleTree;
import com.ebei.admin.model.entity.SysRole;
import com.ebei.admin.service.SysRoleService;
import com.ebei.admin.service.SysUserService;
import com.ebei.common.constant.CommonConstant;
import com.ebei.common.util.Query;
import com.ebei.common.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色服务实现类
 *
 * @author crazypenguin
 * @version 1.0
 * @created 2018/4/17
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 分页查角色列表
     *
     * @param query   查询条件
     * @param wrapper wapper
     * @return page
     */
    @Override
    public Page selectwithDeptPage(Query<Object> query, EntityWrapper<Object> wrapper) {
        query.setRecords(sysRoleMapper.selectRolePage(query, query.getCondition()));
        return query;
    }

    /**
     * 通过部门ID查询角色列表
     *
     * @param deptId 部门ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectListByDeptId(Integer deptId) {
        return sysRoleMapper.selectListByDeptId(deptId);
    }

    /**
     * 获取角色树
     * @param sysRoleEntityWrapper
     * @return
     */
    @Override
    public List<RoleTree> selectListTree(EntityWrapper<SysRole> sysRoleEntityWrapper) {
        return getRoleTree(this.selectList(sysRoleEntityWrapper),-1);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public Boolean deleteByRoleId(String roleId) {

        // 删除当前节点
        SysRole sysRole = this.selectById(roleId);
        sysRole.setDelFlag(CommonConstant.STATUS_DEL);
        boolean result1 = this.updateById(sysRole);

        // 删除子节点
        boolean result2 = true;
        SysRole sysRoleCondition = new SysRole();
        sysRoleCondition.setParentId(Integer.valueOf(roleId));
        sysRoleCondition.setDelFlag(CommonConstant.STATUS_NORMAL);
        List<SysRole> children = this.selectList(new EntityWrapper<>(sysRoleCondition));
        if(children != null && children.size() > 0){
            children.forEach(child -> {
                child.setDelFlag(CommonConstant.STATUS_DEL);
            });
            result2 = this.updateBatchById(children);
        }
        return result1||result2;
    }

    @Override
    public List<RoleDTO> getRoleByUserIdAndRoleCode(Integer userId, String roleCode) {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        params.put("roleCode",roleCode);
        params.put("delFlag",CommonConstant.STATUS_NORMAL);
        return sysRoleMapper.getRoleByUserIdAndRoleCode(params);
    }

    @Override
    public Boolean hasPermission(Integer userId, String roleCode) {
        List<RoleDTO> roleDTOList = getRoleByUserIdAndRoleCode(userId,roleCode);
        if(roleDTOList != null && roleDTOList.size() > 0){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public List<RoleTree> getTree(Integer userId) {
        SysRole condition = new SysRole();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        // 如果是超管
        if(this.hasPermission(userId,Constants.SUPER_ADMIN)){
            return this.selectListTree(new EntityWrapper<>(condition));
        }
        // 根据orgId获取角色
        condition.setOrgId(sysUserService.selectById(userId).getOrgId());
        return this.selectListTree(new EntityWrapper<>(condition));
    }

    @Override
    public Result<Boolean> addRole(SysRole sysRole) {
        // 判断是否是超级管理员新增
        if(!AuthRealm.isSpAdmin()){
            sysRole.setOrgId(AuthRealm.getPrincipal().getOrgId());
        }
        // 如果是新增分类
        if(sysRole.getParentId() != -1){
            // 验证角色编码是否重复
            if(isRepeat(sysRole)){
                return new Result<>(Result.FAIL,"角色编码不可重复");
            }
        }
        sysRole.setCreateTime(new Date());
        sysRole.setUpdateTime(new Date());
        if(this.insert(sysRole)){
            return new Result<>(Result.SUCCESS,"新增成功");
        }else{
            return new Result<>(Result.FAIL,"新增失败");
        }
    }

    @Override
    public Result<Boolean> updateRole(SysRole sysRole) {
        // 获取当前roleCode
        String roleCode = this.selectById(sysRole.getRoleId()).getRoleCode();
        // 没有修改 则不做处理
        if(!roleCode.equals(sysRole.getRoleCode())){
            // 验证重复
            if(isRepeat(sysRole)){
                return new Result<>(Result.FAIL,"角色编码不可重复");
            }
        }
        sysRole.setUpdateTime(new Date());
        if(this.updateById(sysRole)){
            return new Result<>(Result.SUCCESS,"修改成功");
        }else{
            return new Result<>(Result.SUCCESS,"修改失败");
        }
    }

    @Override
    public Result<List<SysRole>> getAllRoles() {
        EntityWrapper<SysRole> ew = new EntityWrapper<>();
        ew.eq("del_flag",CommonConstant.STATUS_NORMAL);
        ew.ne("parent_id",-1);
        // 超管获取所有，非超管按照所属组织id获取
        if(!AuthRealm.isSpAdmin()){
            ew.eq("org_id", AuthRealm.getPrincipal().getOrgId());
        }
        List<SysRole> sysRoles = this.selectList(ew);
        return new Result<>(sysRoles,Result.SUCCESS,"获取成功");
    }

    /**
     * 验证code是否重复
     * @return
     */
    private Boolean isRepeat(SysRole sysRole){
        SysRole condition = new SysRole();
        condition.setRoleCode(sysRole.getRoleCode());
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        List<SysRole> tempList = this.selectList(new EntityWrapper<>(condition));
        if(tempList != null && tempList.size() > 0){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 构建角色树
     * @param roles
     * @param root
     * @return
     */
    private List<RoleTree> getRoleTree(List<SysRole> roles, int root){
        List<RoleTree> roleTreeList = new ArrayList<>();
        RoleTree node;
        for(SysRole sysRole : roles){
            if(sysRole.getRoleId().equals(sysRole.getParentId())){
                continue;
            }
            node = new RoleTree();
            node.setId(sysRole.getRoleId());
            node.setParentId(sysRole.getParentId());
            node.setName(sysRole.getRoleName());
            node.setCode(sysRole.getRoleCode());
            node.setIsFixed(sysRole.getIsFixed());
            roleTreeList.add(node);
        }
        return TreeUtil.bulid(roleTreeList,root);
    }

}
